package com.webapp.blog.web.controller;

/**
 * Created by jinglun on 2016/8/5.
 */

import com.webapp.blog.web.model.Blog;
import com.webapp.blog.web.model.User;
import com.webapp.blog.web.service.BlogService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/blog")
public class BlogController {
    @Resource
    private BlogService blogService;

    //查看所有博文
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String showBlogs(ModelMap modelMap) {
        List<Blog> blogList = blogService.showsBlogs();
        modelMap.addAttribute("blogList", blogList);
        return "Blog/blogs";
    }

    //增加博文
    @RequestMapping(value = "/addblog", method = RequestMethod.GET)
    public String addBlog(){
        return "Blog/addBlog";
    }

    @RequestMapping(value = "/addblogpost", method = RequestMethod.POST)
    public String addBlogPost(@ModelAttribute("blog") Blog blog,HttpServletRequest request){
    	blog.setPubTime(new Date());
    	blog.setUserId(((User)(request.getSession().getAttribute("userInfo"))).getId());
        blogService.insert(blog);
        return "redirect:/rest/blog/list";
    }

    //修改博文
    @RequestMapping(value = "/updateblog/{id}")
    public String updateBlog(@PathVariable("id") long id,ModelMap modelMap){
        Blog blog = blogService.blogdetail(id);
        modelMap.addAttribute("blog",blog);
        return "Blog/updateBlog";
    }

    @RequestMapping(value = "/updateblog/updateBlogPost/{id}",method = RequestMethod.POST)
    public String updateBlogPost(@ModelAttribute("blogp") Blog blog){
        blogService.updateBlog(blog);
        return "redirect:/rest/blog/list";
    }

    //查看博文
    @RequestMapping("/showblog/{id}")
    public String blogdetail(@PathVariable("id") long id,ModelMap modelMap){
        Blog blog = blogService.blogdetail(id);
        modelMap.addAttribute("blog", blog);
        System.out.println(blog.getPubTime());
        return "Blog/blogDetail";
    }

    //删除博文
    @RequestMapping("/deleteblog/{id}")
    public String deleteBlog(@PathVariable("id") long id){
        blogService.deleteBlog(id);
        return "redirect:/rest/blog/list";
    }
}
